# -*- coding: utf-8 -*-
# Echo server program
import socket
import sys
import thread

class socketClass():
    HOST = None               # Symbolic name meaning all available interfaces
    PORT = 2008         # Arbitrary non-privileged port
    s = None    
    def __init__(self):
        
        for res in socket.getaddrinfo(self.HOST, self.PORT, socket.AF_UNSPEC,
                                      socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
            af, socktype, proto, canonname, sa = res
            #print "*******", res   
            try:
                self.s = socket.socket(af, socktype, proto)
            except socket.error, msg:
                self.s = None
                continue
            try:
                self.s.bind(sa)
                self.s.listen(3)
            except socket.error, msg:
                self.s.close()
                self.s = None
                continue
            break
        if self.s is None:
            print 'could not open socket'
            sys.exit(1)

        #conn_v = []
        #addr_v = []
    connections = {}

    def initConnections(self):
        try:
           while 1:    
              conn, addr = self.s.accept()
              #print conn, addr
              #conn_v.append(conn) #not used
              #addr_v.append(addr)
              print 'Connected by', addr
              #conn_v[0].send("sei Ivan!")
              print "Waiting for hostname..."
              data = conn.recv(1024)
              if not data: break
              print data
              self.connections[data] = [conn, addr]
              self.connections[data][0].send("Connected!")
              self.sender(data,"Welcome to "+socket.gethostname())
              thread.start_new_thread(self.loop, (data,))
              #d = raw_input("To send: ")
              #conn.send(d)
              #conn.close()
              #print "closing connection..."
              print self.connections
        except KeyboardInterrupt:
           self.s.close()
           sys.exit(0)
          
    def printTest(self):
       print "Funziona!"

    def sender(self, hostname, data):
       self.connections[hostname][0].send(data)

    def loop(self, hostname):
       print "eccomi "+hostname
       print self.connections
       data = ""
       
       while 1:
          try:
             data = self.connections[hostname][0].recv(1024)
          except KeyError: break
          if not data: break
          print hostname+": "+data
          if data=="BYE":
             del self.connections[hostname]
             print hostname+" disconnected!"
          print self.connections
         
    def closeSocket(self):
        self.s.close()

if __name__=="__main__":
    sc = socketClass()
    sc.initConnections()

